package com.boilermaker.lotterysystem.controller;

import com.boilermaker.lotterysystem.common.pojo.CommonResult;
import com.boilermaker.lotterysystem.common.utils.JacksonUtil;
import com.boilermaker.lotterysystem.controller.param.DrawPrizeParam;
import com.boilermaker.lotterysystem.controller.param.ShowWinningRecordsParam;
import com.boilermaker.lotterysystem.controller.vo.WinningRecordVO;
import com.boilermaker.lotterysystem.service.DrawPrizeService;
import com.boilermaker.lotterysystem.service.dto.WinningRecordDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class DrawPrizeController {

    @Autowired
    private DrawPrizeService drawPrizeService;

    /**
     * 保存中奖信息
     */
    @RequestMapping("/draw-prize")
    public CommonResult<Boolean> drawPrize(@Validated @RequestBody DrawPrizeParam param) {
        log.info("drawPrize DrawPrizeParam:{}", JacksonUtil.writeValueAsString(param));

        drawPrizeService.drawPrize(param);

        return CommonResult.success(true);
    }

    /**
     * 获取中奖者名单
     */
    @RequestMapping("/winning-records/show")
    public CommonResult<List<WinningRecordVO>> showWinningRecords(
            @Validated @RequestBody ShowWinningRecordsParam param) {
        log.info("showWinningRecords ShowWinningRecordsParam:{}", JacksonUtil.writeValueAsString(param));

        List<WinningRecordDTO> winningRecordDTOList = drawPrizeService.getWinningRecords(param);

        return CommonResult.success(convertWinningRecordsDtoToVo(winningRecordDTOList));
    }

    /**
     * DTO -> VO
     */
    private List<WinningRecordVO> convertWinningRecordsDtoToVo(List<WinningRecordDTO> winningRecordDTOList) {

        if (CollectionUtils.isEmpty(winningRecordDTOList)) {
            return List.of();
        }

        return winningRecordDTOList.stream()
                .map(winningRecordDTO -> {
                    WinningRecordVO result = new WinningRecordVO();

                    result.setWinnerId(winningRecordDTO.getWinnerId());
                    result.setWinnerName(winningRecordDTO.getWinnerName());
                    result.setPrizeName(winningRecordDTO.getPrizeName());
                    result.setPrizeTier(winningRecordDTO.getPrizeTier().getMessage());
                    result.setWinningTime(winningRecordDTO.getWinningTime());

                    return result;
                }).collect(Collectors.toList());
    }
}
